/*
 * Copyright (c) 2010, Thiago Campos Viana.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided with the
 *       distribution.
 *     * Neither the name of Thiago Campos Viana nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package lib.db;

import com.mysql.jdbc.DatabaseMetaData;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;
import lib.IniProperties;

/**
 *
 * @author Thiago Campos Viana
 */
public class DataBase {

    private static DataBase singletonObject;
    private Connection conn;
    private Statement statement;

    /** A private Constructor prevents any other class from instantiating. */
    private DataBase() {

        conn = null;



        try {
            InputStream is = new FileInputStream("data/settings/server.ini");
            IniProperties.getInstance().load(is);
            String dbtype = IniProperties.getInstance().getProperty("DatabaseSettings", "DatabaseImplementation");
            String dbname = IniProperties.getInstance().getProperty("DatabaseSettings", "Database");
            String dbserver = IniProperties.getInstance().getProperty("DatabaseSettings", "Server");
            String dbuser = IniProperties.getInstance().getProperty("DatabaseSettings", "User");
            String dbpass = IniProperties.getInstance().getProperty("DatabaseSettings", "Password");
            if (dbtype.equals("javadb")) {

                String folderName = ".ServerDatabase";

                String driver = "org.apache.derby.jdbc.EmbeddedDriver";
                String connectionURL = "jdbc:derby:" + dbname + ";create=true";

                String userHomeDir = System.getProperty("user.home", ".");
                String systemDir = userHomeDir + File.separator + folderName;
                File fileSystemDir = new File(systemDir);
                if (fileSystemDir.exists() == false) {
                    fileSystemDir.mkdir();
                    if (System.getProperty("os.name").contains("Windows")) {
                        try {
                            Runtime rt = Runtime.getRuntime();

                            //put your directory path instead of your_directory_path

                            rt.exec("attrib +h \"" + systemDir + "\"");
                            //int exitVal = proc.exitValue();
                        } catch (Throwable t) {
                        }
                    }
                }
                System.setProperty("derby.system.home", systemDir);

                try {
                    Class.forName(driver);
                    conn = conn = DriverManager.getConnection(connectionURL);

                    statement = conn.createStatement();
                } catch (java.lang.ClassNotFoundException e) {
                }


            } else {
                Class.forName("com.mysql.jdbc.Driver");

                if (dbpass == null) {
                    dbpass = "";
                }
                conn = DriverManager.getConnection("jdbc:mysql://" + dbserver + "/" + dbname + "?"
                        + "user=" + dbuser + "&password=" + dbpass);
                
                statement = conn.createStatement();
            }
            
            ResultSet tables = conn.getMetaData().getTables(null, null, "player", null);
            if (!tables.next()) {
                System.out.println("data/sql/"+dbtype+"/schema.sql");
                
                ScriptRunner sr = new ScriptRunner(conn, true);
                sr.runScript(new FileReader("data/sql/"+dbtype+"/schema.sql"));
                sr.runScript(new FileReader("data/sql/common/cleandata.sql"));
            }
        } catch (Exception ie) {
            ie.printStackTrace();
        }

    }

    public static synchronized DataBase getInstance() {
        if (singletonObject == null || singletonObject.getConnection() == null) {
            singletonObject = new DataBase();
        }

        return singletonObject;
    }

    public ResultSet executeQuery(String query) {
        try {
            return statement.executeQuery(query);
        } catch (Exception e) {
            return null;
        }
    }

    public void execute(String query) {
        try {
            statement.execute(query);
        } catch (Exception e) {
        }
    }

    public Statement getStatement() {
        return statement;
    }

    public Connection getConnection() {
        return conn;
    }

    public void close() {
        try {
            conn.close();
            statement.close();
        } catch (SQLException ex) {
        }
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    public static String dateFormat(Date date, Time time) {
        SimpleDateFormat ft = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat fd = new SimpleDateFormat("dd/MM/yyyy");

        return fd.format(date) + " " + ft.format(time);

    }
}
